package com.grm.datasource.config;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

/**
 * 我们在访问每一个带有DatasourceScope注解的方法时，
 * 都会经过数据源切面DynamicDatasourceAspect，获取到注解上面的 scope的值后，
 * 通过DatasourceContext设置数据源名称，便可实现对数据源的切换。
 *
 * @author gaorimao
 * @date 2022/09/23
 */
@Slf4j
@Aspect
@Component
public class DynamicDatasourceAspect {

    @Pointcut("@annotation(dataSourceScope)")
    public void dynamicPointcut(DatasourceScope dataSourceScope){}

    @Around(value = "dynamicPointcut(dataSourceScope)", argNames = "joinPoint,dataSourceScope")
    public Object dynamicAround(ProceedingJoinPoint joinPoint , DatasourceScope dataSourceScope) throws Throwable {
        String scope = dataSourceScope.scope();
        log.info("datasource = {}",scope);
        DatasourceContext.setDatasource(scope);
        return joinPoint.proceed();
    }
}